import time
import random

from hub import web
from util import html,plot

class HomeHandler(web.WebQuery):
    
    title = 'home@home'

    def __init__(self,serviceName,logger,settings):
        self.logger = logger
        self.settings = settings
        web.WebQuery.__init__(self,serviceName)

    @staticmethod
    def timestamp(when):
        """
        Returns a unix timestamp in a uniform string format
        """
        formatted = time.strftime("%I:%M%p",time.localtime(when)).lower()
        if formatted[0] == '0':
            return formatted[1:]
        else:
            return formatted

    def GET(self,request,session,state,content):
        content.append(html.H1('Temperature'))
        # print the current temperature
        tempLog = self.logger.get('temp')
        if tempLog:
            (when,values) = tempLog.last()
            currentTemp = html.P(
                'The kitchen temperature at %s is %.2f' % (self.timestamp(when),values[0]),
                html.Entity('deg'),'F')
            content.append(currentTemp)
            # display a temperature graph
            tempSeries = plot.PlotSeriesReduced(tempLog.series(),maxPoints=50,smoothing=1.0)
            content.append(plot.PlotFrame(tempSeries,id='tempGraph',
                xaxis='{mode:"time",timeformat:"%h:%M",minTickSize:[1,"minute"]}').html())

        content.append(html.H1('Lighting'))
        lightLog = self.logger.get('light')
        if lightLog:
            (when,values) = lightLog.last()
            currentLight = html.P(
                'The kitchen lighting level at %s is %.0f (1000 corresponds to direct full sun).' %
                (self.timestamp(when),values[0]))
            if values[2]:
                currentLight.append(' Artificial light is being used.')
            content.append(currentLight)
            # display a lighting graph
            ambientSeries = plot.PlotSeriesRaw(lightLog.series(0))
            artificialSeries = plot.PlotSeriesRaw(lightLog.series(2),
                yaxis="2",points="{show:true}",color='"yellow"')
            content.append(plot.PlotFrame(ambientSeries, #artificialSeries,
                id='lightGraph',
                xaxis='{mode:"time",timeformat:"%h:%M",minTickSize:[1,"minute"]}',
                yaxis='{min:0}',
                #y2axis='{min:0.1,max:1.1,minTickSize:2}'
                ).html())
        lwaveLog = self.logger.get('lwave')
        if lwaveLog:
            # display most recent lighting waveform
            (when,samples) = lwaveLog.last()
            waveSeries = plot.PlotSeriesRaw(plot.Enumerated(samples))
            content.append(plot.PlotFrame(waveSeries,id='lwaveGraph').html())
        
        content.append(html.H1('Power'))
        powerLog = self.logger.get('power')
        if powerLog:
            rateFactor = 0.72*float(self.settings.get('local','electricityrate'))
            (when,values) = powerLog.last()
            currentPower = html.P(
                'The kitchen powerstrip is consuming %.0f Watts at %s.'
                % (values[0],self.timestamp(when)),
                ' Maintaining this level for a month would cost $%.2f.' % (rateFactor*values[0]),
                ' Your actual expenses this month are $%.2f.' % (random.uniform(2.,15.)))
            content.append(currentPower)
            # display a power graph
            powerSeries = plot.PlotSeriesRaw(powerLog.series(0))
            powerSeries.scaleY(rateFactor)
            content.append(plot.PlotFrame(powerSeries,id='powerGraph',
                xaxis='{mode:"time",timeformat:"%h:%M",minTickSize:[1,"minute"]}',
                yaxis='{min:0,tickFormatter:function(v,a){return "$"+v.toFixed(2)+"/mo"},minTickSize:0.01}').html())
        pwaveLog = self.logger.get('pwave')
        if pwaveLog:
            # display most recent power waveform
            (when,samples) = pwaveLog.last()
            waveSeries = plot.PlotSeriesRaw(plot.Enumerated(samples))
            content.append(plot.PlotFrame(waveSeries,id='pwaveGraph').html())
        
    def POST(self,request,session,state):
        pass
